import axios from 'axios'
import qs from 'qs'
// import router from '../router'
const http = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, //
  withCredentials: true // 允许发送cookie
  // timeout: 30000 // 请求超时
})

// 请求拦截
http.interceptors.request.use(config => {
  // config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
  config.headers['Content-Type'] = 'application/json'
  return config
})
// 响应拦截
http.interceptors.response.use(response => {
  const res = response.data
  // 登录过期
  if (res.code === 403) {
    // 请求失败
  } else if (!res.success) {
    // 没数据
  }
  return res
})

export default {
  get(url, params = {}, options) {
    return http.get(`${url}?${qs.stringify(params)}`, { ...options })
  },
  post(url, params = {}, options) {
    return http.post(url, params, options)
  },
  put(url, params = {}, options) {
    return http.put(url, params, options)
  },
  delete(url, params = {}, options) {
    return http.delete(`${url}?${qs.stringify(params)}`, { ...options })
  },
  post2(url, params = {}, options) {
    return http.post(url, qs.stringify(params), options)
  },
  post3(url, data = {}, options) {
    return new Promise((resolve, reject) => {
      axios({
        method: 'post',
        url,
        data,
        options
      })
        .then(data => {
          resolve(data)
        })
        .catch(err => {
          reject(err)
        })
    })
  }
}
